
import '@/pages/know-gov/styles/know-gov.scss';
import { Splitter } from '@/components/eai-design';
import { useState, useRef } from 'react';
import DatabaseList, { DatabaseListRef } from './components/database-list';
import ConnectDetail from './components/connect-detail';
import { ConnectionInfo } from '@/types/nl2sql/type';

const Nl2sql = () => {
  const [selectedConnection, setSelectedConnection] = useState<ConnectionInfo | null>(null);
  const [connections, setConnections] = useState<ConnectionInfo[]>([]);
  const databaseListRef = useRef<DatabaseListRef>(null);

  const handleDeleteDatabase = (connectionId: string) => {
    // 处理删除成功后的逻辑
    console.log('删除数据库连接:', connectionId);
  };

  const handleConnectionSelect = (connection: ConnectionInfo | null) => {
    setSelectedConnection(connection);
  };

  const handleConnectionsUpdate = (newConnections: ConnectionInfo[]) => {
    setConnections(newConnections);
  };

  // 刷新数据库连接列表
  const handleRefreshConnections = () => {
    if (databaseListRef.current?.refresh) {
      databaseListRef.current.refresh();
    }
  };

  // 更新选中的连接信息
  const handleUpdateSelectedConnection = (newConnections: ConnectionInfo[]) => {
    if (selectedConnection) {
      // 在更新后的连接列表中找到对应的连接
      const updatedConnection = newConnections.find(
        conn => conn.database_id === selectedConnection.database_id
      );
      if (updatedConnection) {
        setSelectedConnection(updatedConnection);
      }
    }
  };

  return (
    <div className="flex h-full flex-col overflow-hidden bg-[#fff]">
      <div className="flex-1 overflow-hidden">
        <Splitter split="horizontal" className="h-full">
          <Splitter.Panel defaultSize="300" min="200" max="400" className="!p-2">
            {/* 左侧边栏 */}
            <div className="m-3 text-[16px] font-semibold text-gray-900">数据库问答</div>
            <div className="flex h-[calc(100vh-160px)] w-full flex-col border-r border-none bg-white !p-2">
              
              {/* 数据库列表组件 */}
              <DatabaseList
                ref={databaseListRef}
                onDeleteDatabase={handleDeleteDatabase}
                onConnectionsUpdate={(newConnections) => {
                  handleConnectionsUpdate(newConnections);
                  handleUpdateSelectedConnection(newConnections);
                }}
                onConnectionSelect={handleConnectionSelect}
                selectedConnection={selectedConnection}
              />
            </div>
          </Splitter.Panel>
          
          {/* 主内容区 */}
          <div className="flex-1 bg-gray-50">
            <ConnectDetail
              connections={connections}
              selectedConnection={selectedConnection}
              onConnectionSelect={handleConnectionSelect}
              onRefresh={handleRefreshConnections}
            />
          </div>
        </Splitter>
      </div>
    </div>
  );
};

export default Nl2sql;
